<template>
	<view class="sms_container">
		<view class="flex_1 mr10" v-if="sms.loading">
			<input class="mi_input" maxlength="6" type="number"
				v-model="sms.code"
				@input="inputChagne"
				placeholder="请输入验证码" />
		</view>
		<button class="btn flex_1"
				@click="sendSms"
				:disabled="sms.loading" >{{sms.btnText}}</button>
	</view>
</template>

<script setup>
	import { reactive, ref, watch } from "vue";
import { sendVerifySms } from "../../api/public";
import { showToastError, showToastSuccess } from "../../utils/tool";
import { validateMobile } from "../../utils/validate";

	const smsBtnText = '发送验证码'
	const smsTime = 180
	
	const props = defineProps({
		mobile:{type:String, default:''},
	})
	const emits = defineEmits(["codeChange"])
	
	const sms = reactive({
		code:'',
		btnText: smsBtnText,
		loading: false,
	})
	
	watch(() => sms.code, (nv,ov) => {
		if(nv != ov){
			emits("codeChange", nv)
		}
	})
	
	const sendSms = () => {
		let curSmsTime = smsTime
		const {mobile} = props
		if (!mobile || !validateMobile(mobile)){
			showToastError("手机号格式错误")
		    return
		}
		sms.loading = true
		
		sendVerifySms(mobile).then(res => {
			showToastSuccess("验证码已发送")
			
			sms.btnText = `倒计时（${curSmsTime}）`
			let sVal = setInterval(() => {
			    curSmsTime--
				sms.btnText = `倒计时（${curSmsTime}）`
			    if (curSmsTime == 0){
			        clearInterval(sVal)
					sms.btnText = smsBtnText
					sms.loading = false
			    }
			},1000)
		}).catch(err =>{
			sms.loading = false
		})
	}
	
</script>

<style scoped>
	.sms_container{
		width: 100%;
		display: flex;
		justify-content: space-between;
	}
</style>